﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using Microsoft.Practices.ServiceLocation;

namespace Microsoft.Services.Clab.UI.Mvvmc.Composition
{
    public class MefServiceLocator : ServiceLocatorImplBase
    {
        private CompositionContainer container;

        public MefServiceLocator(CompositionContainer container)
        {
            this.container = container;
        }

        protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
        {
            throw new NotImplementedException();
        }

        protected override object DoGetInstance(Type serviceType, string key)
        {
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }

            if (serviceType.Equals(typeof(IController)))
            {
                return this.container.GetExports<IController, IControllerExportMetadata>().Single(c => c.Metadata.LogicalName == key).Value;
            }
            else
            {
                return this.container.GetExports(serviceType, null, null).Single().Value;
            }
        }


        #region Static members
        private static IServiceLocator mefServiceLocatorInstance;

        public static void Initialize(ComposablePartCatalog catalog)
        {
            Initialize(new CompositionContainer(catalog));
        }

        public static void Initialize(CompositionContainer container)
        {
            //container.ComposeExportedValue(container);
            container.ComposeExportedValue(new MefControllerFactory(container) as IControllerFactory);

            mefServiceLocatorInstance = new MefServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => mefServiceLocatorInstance);
        }
        #endregion
    }
}
